/* eslint-disable react/jsx-indent */
import React, { PureComponent } from 'react';
import router from 'umi/router';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Card, message, Row, Col, Modal, Select, Steps, Button, Radio } from 'antd';
import { connect } from 'dva';
import PageHeaderWrapper from '@/components/PageHeaderWrapper'; // 引入头部组件
import styles from '@/utils/utils.less';
import HOCSelect from '@/components/AntDesign/Select';
import AddEmpForm from './AddEmpForm';
import AddEmpInfor from './AddEmpInfor';
import AddMatInfor from './AddMatInfor';

const { Option } = Select;
const { confirm } = Modal;
const FormItem = Form.Item;
const { Step } = Steps;

const steps = [
  {
    title: '查询员工',
    content: 'First-content',
  },
  {
    title: '发起办理',
    content: 'Second-content',
  },
];

const formItemLayouts = {
  labelCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 8,
    },
    xl: { span: 8 },
    xxl: { span: 6 },
  },
  wrapperCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 16,
    },
  },
};

const RadioGroup = Radio.Group;
@connect(
  ({
    card: {
      sendData,
      elementArr,
      empNameList,
      empNameSelect,
      messageData,
      matFileDictItem,
      coltFlag,
    },
    loading,
  }) => ({
    elementArr,
    matFileDictItem,
    coltFlag,
    sendData,
    empNameList,
    empNameSelect,
    messageData,
    loading: loading.effects['card/fetchEmpNameList'],
  })
)
class CardAdd extends PureComponent {
  state = {
    current: 0,
    btnDis: true,
    visNext: false,
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'card/clearEmpName',
      payload: [],
    });
  }

  prev = () => {
    const { current } = this.state;
    const current1 = current - 1;
    this.setState({ current: current1, btnDis: true });
    const { dispatch } = this.props;
    dispatch({
      type: 'card/clearEmpName',
      payload: {},
    });
  };

  save = () => {
    const { form } = this.props;
    form.validateFieldsAndScroll({ force: true }, (err, values) => {
      if (err) return;
      const matlist = [];
      const insCardHdl = {};
      const tempValue = values;
      Object.keys(values).forEach(key => {
        if (key.indexOf('_') !== -1) {
          if (String(tempValue[key].inpType) === '9') {
            let file = '';
            if (tempValue[key].fileList && tempValue[key].fileList.length) {
              tempValue[key].fileList.forEach(item => {
                if (item.response && item.response.success) {
                  file += `${item.response.data},`;
                }
              });
              tempValue[key].inpVal = file ? file.slice(0, file.length - 1) : '';
            }
          }
          tempValue[key].pkgPageDetailId = tempValue[key].pageDetailId;
          matlist.push(tempValue[key]);
        } else if (key === 'matFlag') {
          insCardHdl.matFlag = tempValue[key] ? tempValue[key] : '1';
        } else if (key === 'copyFiles') {
          insCardHdl.copyFiles = tempValue[key];
        } else if (key === 'masterFiles') {
          insCardHdl.masterFiles = tempValue[key];
        }
      });

      const { empNameSelect, dispatch } = this.props;
      insCardHdl.sendId = empNameSelect[0].sendId;
      insCardHdl.source = empNameSelect[0].dataSource;
      insCardHdl.areaId = empNameSelect[0].areaId;
      const param = {
        matlist,
        insCardHdl,
      };

      dispatch({
        type: 'card/addCheckList',
        payload: param,
        callback: response => {
          if (response) {
            if (String(response.data.code) === '201') {
              message.error('该员工正在办理此服务类型，不能新增！');
            } else if (String(response.data.code) === '202') {
              confirm({
                content: '当前人员已办理过此项业务，确定再次办理?',
                okText: '确定',
                cancelText: '取消',
                onOk() {
                  dispatch({
                    type: 'card/addList',
                    payload: param,
                    callback: res => {
                      if (res.success) {
                        router.push(`/socialinsurancemanagement/socialcard/index`);
                      } else {
                        message.warning(res.message);
                      }
                    },
                  });
                },
                onCancel() {},
              });
            } else if (String(response.data.code) === '200') {
              router.push(`/socialinsurancemanagement/socialcard/index`);
            }
          }
        },
      });
    });
  };

  onSelectData = element => {
    const { elementArr, dispatch } = this.props;
    dispatch({
      type: 'card/matInfor',
      payload: { elementArr, element },
    });
  };

  empData = (data, flag) => {
    this.setState({
      btnDis: flag,
    });
    const { dispatch } = this.props;
    dispatch({
      type: 'card/fetchEmpName',
      payload: data,
    });
  };

  empSearch = values => {
    const { dispatch } = this.props;
    dispatch({
      type: 'card/fetchEmpNameList',
      payload: values,
    });
  };

  idVailFunc = values => {
    const { dispatch } = this.props;
    if (values) {
      dispatch({
        type: 'card/fetchEmpNoList',
        payload: values,
        callback: response => {
          this.setState({
            btnDis: response,
          });
        },
      });
    }
  };

  next = () => {
    const { dispatch, empNameSelect } = this.props;
    const { current } = this.state;
    dispatch({
      type: 'card/checkCard',
      payload: { sendId: empNameSelect[0].sendId },
      callback: isDisabled => {
        if (isDisabled) {
          this.setState({ visNext: true });
        } else {
          const current1 = current + 1;
          this.setState({ current: current1 });
          dispatch({
            type: 'card/fetchMatList',
            payload: { serType: 4, serTypeId: '4', areaId: empNameSelect[0].areaId },
          });
          dispatch({
            type: 'card/fetchSendInfor',
            payload: { areaId: empNameSelect[0].areaId,sendId: empNameSelect[0].sendId, dataSource: empNameSelect[0].dataSource },
          });
        }
      },
    });
  };

  okNext = () => {
    const { dispatch, empNameSelect } = this.props;
    const { current } = this.state;
    const current1 = current + 1;
    this.setState({ current: current1, visNext: false });
    dispatch({
      type: 'card/fetchMatList',
      payload: { serType: 4, serTypeId: '4', areaId: empNameSelect[0].areaId },
    });
    dispatch({
      type: 'card/fetchSendInfor',
      payload: { sendId: empNameSelect[0].sendId, dataSource: empNameSelect[0].dataSource },
    });
  };

  cancelNext = () => {
    this.setState({ visNext: false });
  };

  close = () => {
    router.push(`/socialinsurancemanagement/socialcard/index`);
  };

  checkElement = (rule, value, callback) => {
    let tip = '';
    switch (Number(value.inpType)) {
      case 1:
        tip = `请输入不超过30个字的${value.matName}`;
        break;
      case 9:
        tip = `请上传${value.matName}`;
        break;
      case 3:
        tip = `请输入不超过300个字的${value.matName}`;
        break;
      default:
        tip = `请选择${value.matName}`;
        break;
    }
    if (
      Number(value.inpType) !== 9
        ? rule.required && !value.inpVal
        : rule.required && !(value.fileList && value.fileList.length)
    ) {
      callback(tip);
    } else if (Number(value.inpType) === 1 || Number(value.inpType) === 3) {
      if (rule.max < (value.inpVal && value.inpVal.length)) {
        callback(tip);
      } else {
        callback();
      }
    } else {
      callback();
    }
  };

  render() {
    const { current, btnDis, visNext } = this.state;
    const {
      elementArr,
      matFileDictItem,
      sendData,
      empNameList,
      loading,
      empNameSelect,
      messageData,
      coltFlag,
      form: { getFieldDecorator },
    } = this.props;
    const max = val => {
      if (val === 1) return 30;
      if (val === 3) return 300;
      return null;
    };
    const { empSendInfoVo, empBaseInfoVo } = sendData;
    const renderElem = ele =>
      ele && ele.length ? (
        ele.map(element => (
          <Row key={element.pageDetailId}>
            <Col span={8}>
              <FormItem {...formItemLayouts} label={<span> {element.matName}</span>}>
                {getFieldDecorator(`mat_${element.pageDetailId}`, {
                  rules: [
                    {
                      required: Number(element.reqFlag) === 1,
                      validator: this.checkElement,

                      max: max(+element.inpType),
                    },
                  ],
                  initialValue: element,
                })(<AddMatInfor onChange={this.onSelectData} />)}
              </FormItem>
            </Col>
          </Row>
        ))
      ) : (
        <div />
      );

    return (
      <div>
        <PageHeaderWrapper />
        <Card style={{ marginBottom: 12, marginTop: 10 }}>
          <Steps current={current} style={{ width: 327, margin: '0 auto' }}>
            {steps.map(item => (
              <Step key={item.title} title={item.title} />
            ))}
          </Steps>
        </Card>

        <div className={styles.stepsAction}>
          {current === 0 && (
            <Card>
              <AddEmpForm
                empNameList={empNameList}
                empNameSelect={empNameSelect}
                onSearch={this.empSearch}
                empData={this.empData}
                idVailFunc={this.idVailFunc}
                loading={loading}
              />
              <Row style={{ textAlign: 'center', justifyContent: 'center' }}>
                <Button onClick={this.close}>关闭</Button>
                <Button
                  style={{ marginLeft: 30 }}
                  type="primary"
                  onClick={() => this.next()}
                  disabled={btnDis}
                >
                  下一步
                </Button>
              </Row>
            </Card>
          )}
          {current === 1 && (
            <div>
              <div>
                <AddEmpInfor
                  empSendInfoVo={empSendInfoVo}
                  empBaseInfoVo={empBaseInfoVo}
                  loading={loading}
                />
                <Card>
                  {String(coltFlag) === '1' && (
                    <div>
                      <Form>
                        {matFileDictItem && matFileDictItem.length ? (
                          <div>
                            <Row>
                              <Col span={8}>
                                <FormItem {...formItemLayouts} label="原件材料:">
                                  {getFieldDecorator('masterFiles', {
                                    rules: [
                                      {
                                        required: false,
                                        message: '请选择原件材料',
                                      },
                                    ],
                                  })(
                                    <HOCSelect
                                      style={{ width: '100%' }}
                                      mode="multiple"
                                      placeholder="请选择原件材料"
                                      onChange={this.aaa}
                                    >
                                      {matFileDictItem && matFileDictItem.length
                                        ? matFileDictItem.map(options => (
                                            <Option key={options.itemCode}>
                                              {options.itemName}
                                            </Option>
                                          ))
                                        : null}
                                    </HOCSelect>
                                  )}
                                </FormItem>
                              </Col>
                            </Row>
                            <Row>
                              <Col span={8}>
                                <FormItem {...formItemLayouts} label="复印件材料:">
                                  {getFieldDecorator('copyFiles', {
                                    rules: [
                                      {
                                        required: false,
                                        message: '请选择复印件材料',
                                      },
                                    ],
                                  })(
                                    <HOCSelect
                                      style={{ width: '100%' }}
                                      mode="multiple"
                                      placeholder="请选择复印件材料"
                                    >
                                      {matFileDictItem && matFileDictItem.length
                                        ? matFileDictItem.map(options => (
                                            <Option key={options.itemCode}>
                                              {options.itemName}
                                            </Option>
                                          ))
                                        : null}
                                    </HOCSelect>
                                  )}
                                </FormItem>
                              </Col>
                            </Row>
                          </div>
                        ) : null}
                        {renderElem(elementArr)}
                        <div>
                          <Col span={14} offset={1}>
                            <FormItem {...formItemLayouts} label="材料是否完整:">
                              {getFieldDecorator('matFlag', {
                                rules: [
                                  {
                                    required: true,
                                    message: '请选择材料是否完整',
                                  },
                                ],
                                initialValue: '1',
                              })(
                                <RadioGroup>
                                  <Radio value="1">是</Radio>
                                  <Radio value="2">否</Radio>
                                </RadioGroup>
                              )}
                            </FormItem>{' '}
                          </Col>
                        </div>
                      </Form>
                    </div>
                  )}

                  <Row style={{ textAlign: 'center', marginTop: 28, justifyContent: 'center' }}>
                    <Button onClick={this.close}>关闭</Button>
                    <Button style={{ marginLeft: 16 }} onClick={() => this.prev()}>
                      上一步
                    </Button>
                    <Button style={{ marginLeft: 16 }} type="primary" onClick={() => this.save()}>
                      保存
                    </Button>
                  </Row>
                </Card>
              </div>
            </div>
          )}
        </div>
        <Modal title="提示" visible={visNext} onOk={this.okNext} onCancel={this.cancelNext}>
          <p>{Object.keys(messageData).length ? messageData : null}</p>
        </Modal>
      </div>
    );
  }
}
const CardAddform = Form.create()(CardAdd);
export default CardAddform;
